import React, {Component} from 'react';
import { StyleSheet, PanResponder, Dimensions, Animated, PixelRatio, Text, View, ImageBackground, Image, Easing, TouchableOpacity, Platform } from 'react-native';
import PropTypes from 'prop-types';

import Color from '../../config/theme/standard/color';
import fontSize from '../../config/theme/standard/fonts';

export default class SliderButton extends Component {
    constructor(props) {
        super(props);
        this.state = {
            marginLeft: -3,
            width: 27,
            fadeAnim: new Animated.Value(-3), //设置初始值
            widthAnim: new Animated.Value(27),
            isWideScreen: false
        };
    }

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }

    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    componentWillMount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
        this._panResponder = PanResponder.create({
            onStartShouldSetPanResponder: (evt, gestureState) => {
                return true;
            },
            onMoveShouldSetPanResponder:  (evt, gestureState) => {
                return true;
            },
            onPanResponderGrant: (evt, gestureState) => { // 开始手势操作
                if(this.props.disabled == false) {
                    this._onStart();
                }
            },
            onPanResponderMove: (evt, gestureState) => {
                if(this.props.disabled == false) {
                    if(this.state.marginLeft > (Dimensions.get('window').width-75-62) * this.props.range){
                        this.lastX = Dimensions.get('window').width-75-62;
                        this.lastWidth = Dimensions.get('window').width-75-10-27;
                    } else {
                        this.lastX = -3;
                        this.lastWidth = 27;
                        this.setState({
                            width: this.lastWidth + gestureState.dx,
                            marginLeft: this.lastX + gestureState.dx,
                            fadeAnim: new Animated.Value(this.lastX + gestureState.dx),
                            widthAnim: new Animated.Value(this.lastWidth + gestureState.dx),
                        });
                    }
                }
            },
            onPanResponderRelease: (evt, gestureState) => {
                if(this.props.disabled == false) {
                    let left; let width;
                    if (this.state.marginLeft < -3 ) {
                        left = -3;
                        width = 27;
                    } else if (this.state.marginLeft > Dimensions.get('window').width-75-62) {
                        left = Dimensions.get('window').width-75-62;
                        width = Dimensions.get('window').width-75-10-27;
                    } else {
                        left = this.state.marginLeft;
                        width = this.state.width;
                    }

                    this._onRelease();
                }
            },
            onPanResponderTerminate: (evt, gestureState) => {
                if(this.props.disabled == false) {
                    let left; let width;
                    if (this.state.marginLeft < -3 ) {
                        left = -3;
                        width = 27;
                    } else if (this.state.marginLeft > Dimensions.get('window').width-75-62) {
                        left = Dimensions.get('window').width-75-62;
                        width = Dimensions.get('window').width-75-10-27;
                    } else {
                        left = this.state.marginLeft;
                        width = this.state.width;
                    }

                    this._onRelease();
                }
            },
        });
    }

    _onRelease = () =>  {
        Animated.timing(
            this.state.fadeAnim,//初始值
            {
                toValue: this.state.marginLeft > (Dimensions.get('window').width-75-62) * this.props.range? Dimensions.get('window').width-75-62 : -3,
            }, //结束值
        ).start();//开始

        Animated.timing(
            this.state.widthAnim,//初始值
            {
                toValue: this.state.marginLeft > (Dimensions.get('window').width-75-62) * this.props.range? Dimensions.get('window').width-75-10-27 : 27,
            }, //结束值
        ).start();//开始

        let checked;
        if (this.state.marginLeft >= (Dimensions.get('window').width-75-62) * this.props.range ) {
            checked = true
        } else {
            checked = false
        }
        if (typeof this.props.onRelease == 'function') {
            this.props.onRelease(checked);
        }
    };

    _onStart = () => {
        if (typeof this.props.onPress == 'function') {
            this.props.onPress()
        }
    };

    _onReset = () => {
        this.setState({
            marginLeft: -3,
            width: 27,
            fadeAnim: new Animated.Value(-3), //设置初始值
            widthAnim: new Animated.Value(27),
        })
    };

    render() {

        let left; let width;
        if (this.state.marginLeft < -3 ) {
            left = -3;
            width = 27
        } else if (this.state.marginLeft >= Dimensions.get('window').width-75-62) {
            left = Dimensions.get('window').width-75-62;
            width = Dimensions.get('window').width-75-10-27;
        } else {
            left = this.state.fadeAnim;
            width = this.state.widthAnim;
        }

        let background;
        if (this.props.hasBackground) {
            let backgroundImage = this.props.backgroundImage ? this.props.backgroundImage : require('../../assets/sliderbutton_background.png');
            if (this.props.isBackgroundImage) {
                Platform.OS === 'ios' ?
                background = <Animated.View style={[styles.backgroundContainer, {width: width}]} {...this._panResponder.panHandlers}>
                    <Animated.Image source={ backgroundImage }/>
                </Animated.View> :
                background = <Animated.Image source={ backgroundImage } style={[styles.backgroundContainer, {width: width}]} {...this._panResponder.panHandlers}/>
            } else {
                background = <Animated.View style={[styles.backgroundContainer, {backgroundColor: this.props.backgroundColor, width: width}]} {...this._panResponder.panHandlers}/>
            }
        } else {
            background = null;
        }

        let buttonImage = this.props.buttonImage ? this.props.buttonImage : require('../../assets/icon_slidebutton_normal.png');
        let buttonImageDisabled = this.props.buttonImageDisabled ? this.props.buttonImageDisabled : require('../../assets/icon_slidebutton_disabled.png');
        // 适配折叠屏
        const containerStyles = [styles.container]
        const textContainerStyles = [styles.textContainer, Platform.OS == 'harmony' &&{ zIndex:1 }]
        containerStyles.push({
            width: Dimensions.get('window').width-75
        })
        textContainerStyles.push({
            width: Dimensions.get('window').width-75
        })

        return (
            <View>
                <View style={containerStyles}>
                    { background }
                    <View style={textContainerStyles}>
                        <Text style={[styles.text, {color: this.props.disabled ? Color.sliderButton.disabled : Color.sliderButton.text},this.props.textStyle]}>{this.props.text}</Text>
                    </View>
                    <Animated.View style={[
                        {
                            marginTop: this.state.marginTop,
                            marginLeft: left,
                            zIndex: 199
                        }
                    ]}
                                   {...this._panResponder.panHandlers}
                    >
                        <ImageBackground source={require('../../assets/sliderbutton_circle.png')} style={styles.circle}>
                            <Image source={ this.props.disabled ? buttonImageDisabled : buttonImage } style={[styles.arrow, this.props.buttonImageStyle]}/>
                        </ImageBackground>
                    </Animated.View>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flexDirection: 'row',
        height: 60,
        alignItems: 'center',
        borderRadius: 28,
        backgroundColor: Color.sliderButton.background,
        overflow: 'hidden'
    },
    textContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        height: 60,
        position: 'absolute',
        top: 0,
    
    },
    text: {
        fontSize: fontSize.sliderButton.textFontSize,
    },
    circle: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        width: 65,
        height: 65,
    },
    arrow: {
        width: 28,
        height: 28,
        resizeMode: 'cover'
    },
    backgroundContainer: {
        width: 27,
        height: 54,
        justifyContent: 'center',
        alignItems: 'center',
        borderBottomLeftRadius: 54,
        borderTopLeftRadius: 54,
        overflow: 'hidden',
        position: 'absolute',
        marginLeft: 3,
        zIndex: 99
    },
});

SliderButton.propTypes = {
    // 滑动按钮文字
    text: PropTypes.string,
    // 滑动按钮文字样式
    textStyle: PropTypes.any,
    // 是否有背景
    hasBackground: PropTypes.bool,
    // 是否背景图片
    isBackgroundImage: PropTypes.bool,
    // 滑动按钮背景色
    backgroundColor: PropTypes.string,
    // 滑动按钮背景图片
    backgroundImage: PropTypes.any,
    // 按钮位置图片
    buttonImage: PropTypes.any,
    // 按钮位置图片禁用
    buttonImageDisabled: PropTypes.any,
    // 按钮位置图片样式
    buttonImageStyle: PropTypes.any,
    // 是否禁用
    disabled: PropTypes.bool,
    // 滑动确认区域
    range: PropTypes.number,
};

SliderButton.defaultProps = {
    // 滑动按钮文字
    text: '',
    // 滑动按钮文字样式
    textStyle: {},
    // 是否有背景
    hasBackground: true,
    // 是否背景图片
    isBackgroundImage: true,
    // 滑动按钮背景色
    backgroundColor: Color.sliderButton.backgroundMain,
    // 是否禁用
    disabled: false,
    // 滑动确认区域
    range: 1,
};
